<template>
    <el-dialog v-dialogDrag top="5vh" custom-class="rtc-private-video-dialog" 
              :visible.sync="visible" 
              :close-on-click-modal="false" 
              :close-on-press-escape="false" 
              @close="handleClose">
      <div class="camera-dialog-content">
        <!-- Media Container -->
        <div class="media-container">
          <video v-show="!showPhoto" ref="cam" width="320" height="240" 
                muted autoPlay playsInline class="media-preview"></video>
          <canvas v-show="showPhoto" ref="photo" width="320" height="240" 
                class="media-preview"></canvas>
        </div>

        <!-- Controls Section -->
        <div class="camera-controls">
          <!-- Mode Selection -->
          <div v-if="showModeSelection" class="mode-switch">
            <el-button-group class="mode-buttons">
              <el-button type="primary" @click="selectMode('photo')"
                        icon="el-icon-camera-solid" circle></el-button>
              <el-button type="primary" @click="selectMode('video')" 
                        icon="el-icon-video-camera-solid" circle></el-button>
            </el-button-group>
          </div>

          <!-- Photo Controls -->
          <div v-if="!showModeSelection && mode === 'photo'" 
              class="action-buttons">
            <el-button type="primary" @click="takePhoto" 
                      icon="el-icon-camera" circle></el-button>
            <el-button type="success" @click="selectPhoto" 
                      icon="el-icon-check" circle></el-button>
            <el-button type="danger" @click="cancelPhoto" 
                      icon="el-icon-close" circle></el-button>
          </div>

          <!-- Video Controls -->
          <div v-if="!showModeSelection && mode === 'video'" 
              class="action-buttons">
            <el-button :type="recording ? 'danger' : 'primary'" 
                      :icon="recording ? 'el-icon-video-pause' : 'el-icon-video-play'" 
                      @click="toggleRecording" circle></el-button>
            <el-button type="warning" @click="restartRecording" 
                      :disabled="!recording && recordedBlobs.length === 0" 
                      icon="el-icon-refresh-left" circle></el-button>
            <el-button type="success" @click="selectVideo" 
                      :disabled="recordedBlobs.length === 0" 
                      icon="el-icon-finished" circle></el-button>
          </div>
        </div>
      </div>
    </el-dialog>
</template>
  
<script>
  import ImCamera from "../../api/camera";
  
  export default {
    name: 'CameraDialog',
    props: {
      visible: {
        type: Boolean,
        required: true
      }
    },
    data() {
      return {
        mode: 'photo',
        showPhoto: false,
        showModeSelection: true,
        recordedBlobs: [],
        mediaRecorder: null,
        localStream: null,
        camera: new ImCamera(),
        recording: false 
      }
    },
    watch: {
      visible(newVal) {
        if (newVal) {
          this.initializeCamera();
        }
      }
    },
    methods: {
      selectMode(newMode) {
        this.mode = newMode;
        this.showModeSelection = false;
        
        if (newMode === 'video') {
          this.$refs.cam.controls = false;
        } else {
          this.cancelPhoto();
        }
      },
    async initializeCamera() {
      try {
        if (!this.localStream) {
          const stream = await this.camera.openVideo();
          this.localStream = stream;
          this.$refs.cam.srcObject = stream;
          this.$refs.cam.muted = true;
        }
      } catch (e) {
        this.$message.error("Camera failed to open");
        this.$emit('update:visible', false);
        console.error("Camera error:", e.message);
      }
    },
  
    takePhoto() {
        const ctx = this.$refs.photo.getContext('2d');
        ctx.drawImage(this.$refs.cam, 0, 0, 300, 300);
        this.showPhoto = true;
    },
  
    selectPhoto() {
        this.$refs.photo.toBlob(blob => {
          this.$emit('photo-selected', blob);
          this.handleClose();
        });
    },
  
    cancelPhoto() {
        this.showPhoto = false;
    },
  
    toggleRecording() {
        if (this.recording) {
          this.stopRecording();
        } else {
          this.startRecording();
        }
    },
  
    startRecording() {
        this.recordedBlobs = [];
        this.mediaRecorder = new MediaRecorder(this.localStream, { 
          mimeType: 'video/webm;codecs=vp9' 
        });
  
        this.mediaRecorder.ondataavailable = e => {
          if (e.data.size > 0) this.recordedBlobs.push(e.data);
        };
  
        this.mediaRecorder.start(100);
        this.recording = true; 
    },
  
    stopRecording() {
        this.mediaRecorder.stop();
        this.recording = false; 
      },
  
    restartRecording() {
        this.stopRecording();
        this.recordedBlobs = [];
        this.$refs.cam.srcObject = this.localStream;
      },
  
    selectVideo() {
        const blob = new Blob(this.recordedBlobs, { type: 'video/webm' });
        this.$emit('video-selected', blob);
        this.handleClose();
      },
  
      handleClose() {
      this.showModeSelection = true;
      this.mode = 'photo';
      this.showPhoto = false;
      this.recordedBlobs = [];
      this.recording = false;

      if (this.mediaRecorder) {
        this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
        this.mediaRecorder = null;
      }

      if (this.localStream) {
        this.localStream.getTracks().forEach(track => track.stop());
        this.localStream = null;
      }

      if (this.$refs.cam) {
        this.$refs.cam.srcObject = null;
        this.$refs.cam.load();
      }

      this.camera.close();
      
      this.$emit('update:visible', false);
      this.$emit('close');
    }
  },
    beforeDestroy() {
      if (this.localStream) {
        this.localStream.getTracks().forEach(track => track.stop());
      }
    }
  }
</script>
  
<style lang="scss">
.rtc-private-video-dialog {
  width: 500px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);

  .camera-dialog-content {
    padding: 20px;
    background: #f8f9fa;

    .media-container {
      margin: 15px 0;
      position: relative;
      
      .media-preview {
        border: 2px solid #e9ecef;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        background: #000;
      }
    }

    .camera-controls {
      width: 100%;
      padding: 20px 0 0;
      border-top: 1px solid #dee2e6;

      .mode-buttons {
        display: flex;
        justify-content: center;
        gap: 30px;

        .el-button {
          width: 48px;
          height: 48px;
          font-size: 20px;
        }
      }

      .action-buttons {
        display: flex;
        justify-content: center;
        gap: 25px;

        .el-button {
          width: 56px;
          height: 56px;
          font-size: 24px;
          transition: all 0.3s ease;

          &:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }
}
</style>